package com.yingdong.centerserver;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yingdong.centerserver.net.CenterServerHandlerNetty4;
import com.yingdong.centerserver.net.frager.CenterServerPacketDefragerNetty4;
import com.yingdong.gateserver.innter.service.ConfigService;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class CenterServer {
	static Log logger = LogFactory.getLog(CenterServer.class);

	public static void main(String[] args) {

		ConfigService.init();
		EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap(); // (2)
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
					.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new CenterServerPacketDefragerNetty4(), new CenterServerHandlerNetty4());
						}
					});

			b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
			b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);// 关键是这句
			b.option(ChannelOption.TCP_NODELAY, Boolean.TRUE);
			b.childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE);
			b.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
			b.childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE);
			// Bind and start to accept incoming connections.
			ChannelFuture f = b.bind(ConfigService.getPropertyInt("center.server.port")).sync(); // (7)
		} catch (Exception e) {
			logger.info("", e);
		}
		try {
			GlobalInitManager.init();
		} catch (Exception e) {
			logger.error("", e);
		}

	}
}
